using RAG.Application.Interfaces;
using RAG.Application.Dtos;
using RAG.Application.Commands;
using RAG.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace RAG.Application.Services;

/// <summary>
/// 系统服务实现
/// </summary>
public class AppSystemService : IAppSystemService
{
    private readonly RagDbContext _db;

    public AppSystemService(RagDbContext db)
    {
        _db = db;
    }

    /// <summary>
    /// 获取系统统计信息
    /// </summary>
    public async Task<ApiResult> GetSystemStatisticsAsync()
    {
        try
        {
            var totalUsers = await _db.Users.Where(u => !u.IsDeleted).CountAsync();
            var activeUsers = await _db.Users.Where(u => !u.IsDeleted && u.IsActive).CountAsync();
            var totalDocuments = await _db.Documents.CountAsync();
            var totalConversations = await _db.Conversations.CountAsync();
            var totalKnowledgeBases = await _db.KnowledgeBases.CountAsync();
            
            // 计算存储使用量
            var totalStorageUsed = await _db.Documents.SumAsync(d => d.DocumentFileSize);
            
            // 文档状态统计
            var documentStatusCounts = await _db.Documents
                .GroupBy(d => d.DocumentStatus)
                .Select(g => new { Status = g.Key, Count = g.Count() })
                .ToDictionaryAsync(x => x.Status, x => x.Count);
            
            // 对话模型统计
            var conversationModelCounts = await _db.Conversations
                .GroupBy(c => c.ConversationModel)
                .Select(g => new { Model = g.Key, Count = g.Count() })
                .ToDictionaryAsync(x => x.Model, x => x.Count);

            var statistics = new SystemStatisticsDto
            {
                TotalUsers = totalUsers,
                ActiveUsers = activeUsers,
                TotalDocuments = totalDocuments,
                TotalConversations = totalConversations,
                TotalKnowledgeBases = totalKnowledgeBases,
                TotalStorageUsed = totalStorageUsed,
                DocumentStatusCounts = documentStatusCounts,
                ConversationModelCounts = conversationModelCounts
            };

            return ApiResult.Success("获取系统统计信息成功", statistics);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取系统统计信息失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取系统分析报告
    /// </summary>
    public async Task<ApiResult> GetSystemAnalyticsAsync()
    {
        try
        {
            // 最近7天的数据
            var sevenDaysAgo = DateTime.UtcNow.AddDays(-7);
            
            var dailyConversations = await _db.Conversations
                .Where(c => c.CreatedAt >= sevenDaysAgo)
                .GroupBy(c => c.CreatedAt.Date)
                .Select(g => new { Date = g.Key, Count = g.Count() })
                .OrderBy(x => x.Date)
                .ToListAsync();

            var dailyDocuments = await _db.Documents
                .Where(d => d.CreatedAt >= sevenDaysAgo)
                .GroupBy(d => d.CreatedAt.Date)
                .Select(g => new { Date = g.Key, Count = g.Count() })
                .OrderBy(x => x.Date)
                .ToListAsync();

            var topModels = await _db.Conversations
                .GroupBy(c => c.ConversationModel)
                .Select(g => new { Model = g.Key, Count = g.Count() })
                .OrderByDescending(x => x.Count)
                .Take(5)
                .ToListAsync();

            var averageResponseTime = await _db.Conversations
                .Where(c => c.LatencyMs > 0)
                .AverageAsync(c => c.LatencyMs);

            var analytics = new
            {
                DailyConversations = dailyConversations,
                DailyDocuments = dailyDocuments,
                TopModels = topModels,
                AverageResponseTime = averageResponseTime,
                AnalysisPeriod = "最近7天"
            };

            return ApiResult.Success("获取系统分析报告成功", analytics);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取系统分析报告失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取向量化处理状态
    /// </summary>
    public async Task<ApiResult> GetVectorizationStatusAsync()
    {
        try
        {
            var processingCount = await _db.Documents
                .Where(d => d.DocumentStatus == "processing")
                .CountAsync();

            var completedCount = await _db.Documents
                .Where(d => d.DocumentStatus == "completed")
                .CountAsync();

            var errorCount = await _db.Documents
                .Where(d => d.DocumentStatus == "error")
                .CountAsync();

            var uploadedCount = await _db.Documents
                .Where(d => d.DocumentStatus == "uploaded")
                .CountAsync();

            var totalChunks = await _db.DocumentChunks.CountAsync();
            var totalVectors = await _db.Vectors.CountAsync();

            var status = new
            {
                ProcessingCount = processingCount,
                CompletedCount = completedCount,
                ErrorCount = errorCount,
                UploadedCount = uploadedCount,
                TotalChunks = totalChunks,
                TotalVectors = totalVectors,
                ProcessingRate = completedCount > 0 ? (double)completedCount / (completedCount + errorCount) * 100 : 0
            };

            return ApiResult.Success("获取向量化处理状态成功", status);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取向量化处理状态失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取仪表盘统计数据
    /// </summary>
    public async Task<ApiResult> GetDashboardStatisticsAsync()
    {
        try
        {
            var now = DateTime.UtcNow;
            var lastMonth = now.AddMonths(-1);
            var currentMonthStart = new DateTime(now.Year, now.Month, 1);
            var lastMonthStart = new DateTime(lastMonth.Year, lastMonth.Month, 1);

            // 当前数据
            var totalUsers = await _db.Users.Where(u => !u.IsDeleted).CountAsync();
            var totalKnowledgeBases = await _db.KnowledgeBases.CountAsync();
            var totalDocuments = await _db.Documents.CountAsync();
            
            // 从现有的conversations表获取问答总数
            var totalQA = await _db.Conversations.CountAsync();

            // 本月数据
            var currentMonthUsers = await _db.Users
                .Where(u => !u.IsDeleted && u.CreatedAt >= currentMonthStart)
                .CountAsync();
            var currentMonthKnowledgeBases = await _db.KnowledgeBases
                .Where(k => k.CreatedAt >= currentMonthStart)
                .CountAsync();
            var currentMonthDocuments = await _db.Documents
                .Where(d => d.CreatedAt >= currentMonthStart)
                .CountAsync();
            
            var currentMonthQA = await _db.Conversations
                .Where(c => c.CreatedAt >= currentMonthStart)
                .CountAsync();

            // 上月数据
            var lastMonthUsers = await _db.Users
                .Where(u => !u.IsDeleted && u.CreatedAt >= lastMonthStart && u.CreatedAt < currentMonthStart)
                .CountAsync();
            var lastMonthKnowledgeBases = await _db.KnowledgeBases
                .Where(k => k.CreatedAt >= lastMonthStart && k.CreatedAt < currentMonthStart)
                .CountAsync();
            var lastMonthDocuments = await _db.Documents
                .Where(d => d.CreatedAt >= lastMonthStart && d.CreatedAt < currentMonthStart)
                .CountAsync();
            
            var lastMonthQA = await _db.Conversations
                .Where(c => c.CreatedAt >= lastMonthStart && c.CreatedAt < currentMonthStart)
                .CountAsync();

            // 计算环比增长率
            var userGrowthRate = lastMonthUsers > 0 ? (double)(currentMonthUsers - lastMonthUsers) / lastMonthUsers * 100 : 0;
            var knowledgeBaseGrowthRate = lastMonthKnowledgeBases > 0 ? (double)(currentMonthKnowledgeBases - lastMonthKnowledgeBases) / lastMonthKnowledgeBases * 100 : 0;
            var documentGrowthRate = lastMonthDocuments > 0 ? (double)(currentMonthDocuments - lastMonthDocuments) / lastMonthDocuments * 100 : 0;
            var qaGrowthRate = lastMonthQA > 0 ? (double)(currentMonthQA - lastMonthQA) / lastMonthQA * 100 : 0;

            var dashboardData = new
            {
                TotalUsers = new
                {
                    Value = totalUsers,
                    GrowthRate = Math.Round(userGrowthRate, 1),
                    Trend = userGrowthRate >= 0 ? "up" : "down"
                },
                TotalKnowledgeBases = new
                {
                    Value = totalKnowledgeBases,
                    GrowthRate = Math.Round(knowledgeBaseGrowthRate, 1),
                    Trend = knowledgeBaseGrowthRate >= 0 ? "up" : "down"
                },
                TotalDocuments = new
                {
                    Value = totalDocuments,
                    GrowthRate = Math.Round(documentGrowthRate, 1),
                    Trend = documentGrowthRate >= 0 ? "up" : "down"
                },
                TotalQA = new
                {
                    Value = totalQA,
                    GrowthRate = Math.Round(qaGrowthRate, 1),
                    Trend = qaGrowthRate >= 0 ? "up" : "down"
                },
                LastUpdated = now
            };

            return ApiResult.Success("获取仪表盘统计数据成功", dashboardData);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取仪表盘统计数据失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取系统健康状态
    /// </summary>
    public async Task<ApiResult> GetSystemHealthStatusAsync()
    {
        try
        {
            var startTime = DateTime.UtcNow;
            
            // 检查数据库连接
            var dbConnectionOk = await _db.Database.CanConnectAsync();
            
            // 检查关键表是否存在数据
            var usersCount = await _db.Users.CountAsync();
            var documentsCount = await _db.Documents.CountAsync();
            var conversationsCount = await _db.Conversations.CountAsync();
            
            // 检查向量服务状态（通过检查向量表）
            var vectorsCount = await _db.Vectors.CountAsync();
            var vectorServiceOk = vectorsCount >= 0; // 如果能查询到数量，说明向量服务正常
            
            // 检查文件存储状态（通过检查文档表）
            var fileStorageOk = documentsCount >= 0; // 如果能查询到数量，说明文件存储正常
            
            var endTime = DateTime.UtcNow;
            var responseTime = (endTime - startTime).TotalMilliseconds;

            var healthStatus = new
            {
                // 前端期望的字段名和值
                systemHealth = dbConnectionOk ? "normal" : "abnormal",
                databaseStatus = dbConnectionOk ? "connected" : "disconnected",
                vectorServiceStatus = vectorServiceOk ? "available" : "unavailable",
                fileStorageStatus = fileStorageOk ? "normal" : "abnormal",
                
                // 保留原有字段以兼容
                SystemStatus = dbConnectionOk ? "正常" : "异常",
                ResponseTime = $"{responseTime:F0}ms",
                LastCheck = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"),
                DatabaseConnection = dbConnectionOk ? "正常" : "异常",
                KeyTablesStatus = new
                {
                    Users = usersCount >= 0 ? "正常" : "异常",
                    Documents = documentsCount >= 0 ? "正常" : "异常",
                    Conversations = conversationsCount >= 0 ? "正常" : "异常"
                }
            };

            return ApiResult.Success("获取系统健康状态成功", healthStatus);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取系统健康状态失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取系统详细信息
    /// </summary>
    public async Task<ApiResult> GetSystemDetailedInfoAsync()
    {
        try
        {
            var process = System.Diagnostics.Process.GetCurrentProcess();
            var startTime = process.StartTime.ToUniversalTime();
            var uptime = DateTime.UtcNow - startTime;
            
            var systemInfo = new
            {
                SystemVersion = "1.0.0",
                RunningTime = $"{uptime.Days}.{uptime.Hours:D2}:{uptime.Minutes:D2}:{uptime.Seconds:D2}.{uptime.Milliseconds:D7}",
                MemoryUsage = $"{process.WorkingSet64 / 1024 / 1024:F0} MB",
                ProcessId = process.Id,
                Framework = Environment.Version.ToString(),
                OS = Environment.OSVersion.ToString(),
                ProcessorCount = Environment.ProcessorCount,
                TotalPhysicalMemory = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 1024 / 1024 / 1024,
                StartTime = startTime.ToString("yyyy-MM-dd HH:mm:ss")
            };

            return ApiResult.Success("获取系统详细信息成功", systemInfo);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取系统详细信息失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取向量化详细状态
    /// </summary>
    public async Task<ApiResult> GetVectorizationDetailedStatusAsync()
    {
        try
        {
            var processingCount = await _db.Documents
                .Where(d => d.DocumentStatus == "processing")
                .CountAsync();

            var completedCount = await _db.Documents
                .Where(d => d.DocumentStatus == "completed")
                .CountAsync();

            var errorCount = await _db.Documents
                .Where(d => d.DocumentStatus == "error")
                .CountAsync();

            var uploadedCount = await _db.Documents
                .Where(d => d.DocumentStatus == "uploaded")
                .CountAsync();

            var totalChunks = await _db.DocumentChunks.CountAsync();
            var totalVectors = await _db.Vectors.CountAsync();

            var processingRate = (completedCount + errorCount) > 0 ? 
                (double)completedCount / (completedCount + errorCount) * 100 : 0;

            var vectorizationStatus = new
            {
                ProcessingStatus = processingCount > 0 ? "处理中" : "空闲",
                QueueLength = processingCount,
                ProcessingProgress = $"{processingRate:F0}%",
                TotalDocuments = completedCount + errorCount + uploadedCount + processingCount,
                CompletedDocuments = completedCount,
                ErrorDocuments = errorCount,
                ProcessingDocuments = processingCount,
                TotalChunks = totalChunks,
                TotalVectors = totalVectors,
                SuccessRate = processingRate
            };

            return ApiResult.Success("获取向量化详细状态成功", vectorizationStatus);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取向量化详细状态失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取系统分析报告（扩展版）
    /// </summary>
    public async Task<ApiResult> GetSystemAnalyticsExtendedAsync()
    {
        try
        {
            var now = DateTime.UtcNow;
            var sevenDaysAgo = now.AddDays(-7);
            var thirtyDaysAgo = now.AddDays(-30);

            // 用户活跃度
            var activeUsers = await _db.Users
                .Where(u => !u.IsDeleted && u.IsActive)
                .CountAsync();
            var totalUsers = await _db.Users.Where(u => !u.IsDeleted).CountAsync();
            var userActivityRate = totalUsers > 0 ? (double)activeUsers / totalUsers * 100 : 0;

            // 问答数量
            var totalQA = await _db.Conversations.CountAsync();
            var recentQA = await _db.Conversations
                .Where(c => c.CreatedAt >= sevenDaysAgo)
                .CountAsync();
            var qaGrowthRate = totalQA > 0 ? (double)recentQA / totalQA * 100 : 0;

            // 文档处理
            var totalDocuments = await _db.Documents.CountAsync();
            var processedDocuments = await _db.Documents
                .Where(d => d.DocumentStatus == "completed")
                .CountAsync();
            var documentProcessingRate = totalDocuments > 0 ? (double)processedDocuments / totalDocuments * 100 : 0;

            // 系统性能
            var averageResponseTime = await _db.Conversations
                .Where(c => c.LatencyMs > 0)
                .AverageAsync(c => c.LatencyMs);
            var performanceScore = averageResponseTime > 0 ? Math.Max(0, 100 - averageResponseTime / 10) : 100;

            var analytics = new
            {
                UserActivity = new
                {
                    Value = activeUsers,
                    Percentage = $"{userActivityRate:F0}%",
                    TotalUsers = totalUsers
                },
                QAQty = new
                {
                    Value = totalQA,
                    Percentage = $"{qaGrowthRate:F0}%",
                    RecentQA = recentQA
                },
                DocumentProcessing = new
                {
                    Value = processedDocuments,
                    Percentage = $"{documentProcessingRate:F0}%",
                    TotalDocuments = totalDocuments
                },
                SystemPerformance = new
                {
                    Value = $"{performanceScore:F0}%",
                    Percentage = $"{performanceScore:F0}%",
                    AverageResponseTime = $"{averageResponseTime:F0}ms"
                }
            };

            return ApiResult.Success("获取系统分析报告成功", analytics);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取系统分析报告失败: {ex.Message}");
        }
    }
}
